package edu.kit.aifb.ldstream.learner.query;

import java.util.concurrent.Callable;

import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.impl.MutableTupleQueryResult;

import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;

public class SPARQLQuery implements Callable<MutableTupleQueryResult>{

	private RepositoryConnection connection;
	private String query;
	// Automatically closes the connection
	private boolean autoClose = true;
	private boolean inferencing;
	
	public SPARQLQuery(RepositoryConnection connection, String query, boolean inferencing){
		
		this.connection = connection;
		this.query = query;
		this.inferencing = inferencing;
	}
	
	
	@Override
	public MutableTupleQueryResult call()  {

		TupleQuery tupleQuery;
		MutableTupleQueryResult result = null;
		try {
			tupleQuery = this.connection.prepareTupleQuery(QueryLanguage.SPARQL, this.query);
			tupleQuery.setIncludeInferred(this.inferencing);
			result = new MutableTupleQueryResult(tupleQuery.evaluate());
		} catch (RepositoryException e) {
			e.printStackTrace();
		} catch(MalformedQueryException e){
			e.printStackTrace();
		} catch (QueryEvaluationException e) {
			e.printStackTrace();
		} finally{
			if(autoClose){
				try {
					this.connection.close();
				} catch (RepositoryException e) {
					e.printStackTrace();
				}
			}
		}
		
		
		
		return result;
	}
	
	public void disableAutoClose(){
		this.autoClose = false;
	}

}
